package io.jee.runshan.handler;

import io.jee.runshan.domain.KeywordAsk;
import io.jee.runshan.domain.VoiceAsk;
import io.jee.runshan.domain.remote.weixin.InputMessage;
import io.jee.runshan.domain.remote.weixin.OutputTextMessage;
import io.jee.runshan.domain.remote.weixin.WeixinUserInfo;
import io.jee.runshan.service.IKeywordAskService;
import io.jee.runshan.service.IVoiceAskService;
import io.jee.runshan.service.remote.weixin.IUserInfoService;
import io.jee.runshan.utils.SpringHolder;
import io.jee.runshan.utils.WeixinConstant;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 关键字匹配处理
 * @author qinling.zhu
 *
 */
public class WeixinReceiverVoiceHandler {
	private IVoiceAskService voiceAskService = SpringHolder.getBean(IVoiceAskService.class);
	private IUserInfoService wxUserInfoService = SpringHolder.getBean(IUserInfoService.class);
	private IKeywordAskService keywordAskService = SpringHolder.getBean(IKeywordAskService.class);

	public String excute(InputMessage inputMsg, HttpServletRequest request) throws Exception {
		WeixinUserInfo wxUserinfo = wxUserInfoService.getWeixinUserInfo(inputMsg.getFromUserName());
		VoiceAsk voiceAsk = new VoiceAsk();
		voiceAsk.setWxOpenid(inputMsg.getFromUserName());
		voiceAsk.setFormat(inputMsg.getFormat());
		voiceAsk.setPublishTime(new Date(inputMsg.getCreateTime()*1000));
		voiceAsk.setMsgId(inputMsg.getMsgId());
		voiceAsk.setRecognition(inputMsg.getRecognition());
		voiceAsk.setWxNikeName(wxUserinfo.getNickname());
		
		String rootPath = "/upload";
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		String path = rootPath + "/voice/" + dateformat.format(new Date());//如：/productImg/2015-01-21
		String realPath = request.getSession().getServletContext().getRealPath(path); 
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		URIBuilder uriBuilder = new URIBuilder("http://file.api.weixin.qq.com/cgi-bin/media/get");
		uriBuilder.addParameter("access_token", WeixinConstant.token());
		uriBuilder.addParameter("media_id", inputMsg.getMediaId());
		HttpGet httpGet = new HttpGet(uriBuilder.build());
		CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
		String filename = getFileName(httpResponse);
		byte[] b = EntityUtils.toByteArray(httpResponse.getEntity());
		HttpClientUtils.closeQuietly(httpClient);
		File file = new File(realPath);
		if(!file.exists()) {
			file.mkdirs();
		}
		File source = new File(file, filename);
		FileOutputStream out = new FileOutputStream(source);
		out.write(b);
		out.flush();
		out.close();
		String newfilename = filename.substring(0, filename.lastIndexOf("."))+".mp3";
		File target = new File(file, newfilename);
		
		AudioAttributes audio = new AudioAttributes();
		audio.setCodec("libmp3lame");
		
		EncodingAttributes attrs = new EncodingAttributes();
		attrs.setFormat("mp3");
		attrs.setAudioAttributes(audio);
		
		Encoder encoder = new Encoder();
		try{
			encoder.encode(source, target, attrs);
		} catch (EncoderException e){
			e.printStackTrace();
		}
		voiceAsk.setVoiceUrl(path+"/"+newfilename);
		
		KeywordAsk keywordAsk = keywordAskService.findKeyword(voiceAsk.getRecognition());
		OutputTextMessage outputMsg = new OutputTextMessage();
		if (keywordAsk != null) {
			outputMsg.setContent(keywordAsk.getReplyContent());
			keywordAsk.getReplyContent();
			voiceAsk.setIsRead(1);
			voiceAsk.setReplyState(2);
		} else {
			outputMsg.setContent("您的问题我们暂时不能自动为您解答，请等待人工坐席为您服务！");
		}
		voiceAskService.save(voiceAsk);
		return WeixinConstant.genMessage(outputMsg, inputMsg);
	}
	
	private static String getFileName(HttpResponse response) {
        Header contentHeader = response.getFirstHeader("Content-Disposition");  
        String filename = null;  
        if (contentHeader != null) {  
            HeaderElement[] values = contentHeader.getElements();  
            if (values.length == 1) {  
                NameValuePair param = values[0].getParameterByName("filename");  
                if (param != null) {  
                    try {  
                        //filename = new String(param.getValue().toString().getBytes(), "utf-8");  
                        //filename=URLDecoder.decode(param.getValue(),"utf-8");  
                        filename = param.getValue();  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }  
        return filename;  
    }  
}
